package com.enjoy.concurrent.ch1.base;

import lombok.extern.slf4j.Slf4j;

/**
 * 测试sleep对锁的影响:sleep不会释放锁
 */
@Slf4j
public class SleepLock {

    private final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        SleepLock sleepLock = new SleepLock();

        ThreadSleep threadSleep = sleepLock.new ThreadSleep();
        threadSleep.setName("threadSleep");
        ThreadNotSleep threadNotSleep = sleepLock.new ThreadNotSleep();
        threadNotSleep.setName("threadNotSleep");

        threadSleep.start();
        threadNotSleep.start();

        Thread.sleep(1000);
    }

    private class ThreadSleep extends Thread {
        @Override
        public void run() {
            try {
                synchronized (lock) {
                    log.debug("take the lock");
                    Thread.sleep(5000);
                    log.debug("finish the work");
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    private class ThreadNotSleep extends Thread {
        @Override
        public void run() {
            long l = System.currentTimeMillis();
            log.debug("start");
            synchronized (lock) {
                log.debug("take the lock time " + (System.currentTimeMillis() - l) / 1000 + "s");
            }
            log.debug("finish the work");
        }
    }
}
